package cn.fr.controller;

import cn.fr.config.ConfConstConfig;
import cn.fr.entity.LoginInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/picture")
public class GetPictureUrlsController {
    private static Logger logger = LoggerFactory.getLogger("PROJECT_LOGGER");
    private  RestTemplate restTemplate;
    private  ConfConstConfig confConstConfig;
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
    @Autowired
    public void setConfConstConfig(ConfConstConfig confConstConfig) {
        this.confConstConfig = confConstConfig;
    }
    @Autowired
    public void setRestHighLevelClient(RestHighLevelClient restHighLevelClient) {
        this.restHighLevelClient = restHighLevelClient;
    }

    @GetMapping("/url/{id}")
    public ResponseEntity getPicById(@PathVariable Long id) {
        HashMap params = new HashMap<>();
        logger.info("日志打印id："+id);
        params.put("q", id); //
        String url = confConstConfig.getPicturePath();
        ResponseEntity responseEntity = restTemplate.getForEntity(url+"={q}", String.class, params);
        String res = (String) responseEntity.getBody();
        JSONObject jsonObject = JSON.parseObject(res);
        JSONArray items = (JSONArray) jsonObject.get("items");
        List<LoginInfo> lists = JSON.parseObject(items.toJSONString(), new TypeReference<List<LoginInfo>>() {
        });
        for (int i =0 ;i< lists.size();i++) {
            logger.info(lists.get(i).getAvatar_url());
        }
        return responseEntity;
    }

    @GetMapping("/savePicById/{id}")
    public void savePicById(@PathVariable Long id) throws IOException {
        HashMap params = new HashMap<>();
        logger.info("日志打印id："+id);
        params.put("v", id); //
        String url = "https://avatars.githubusercontent.com/u/3157269?v=";
        ResponseEntity<byte[]> response = restTemplate.exchange(
                "https://avatars.githubusercontent.com/u/3157269?v=4",
                HttpMethod.GET,
                null,
                byte[].class
        );
        byte[] fileData = response.getBody();
        FileOutputStream fos = new FileOutputStream("zttfile.png");
        fos.write(fileData);
        fos.close();
    }
    @PostMapping("/transToEs")
    public void transToEs() throws Exception{
        ResponseEntity<byte[]> response = restTemplate.exchange(
                "https://avatars.githubusercontent.com/u/3157269?v=4",
                HttpMethod.GET,
                null,
                byte[].class
        );
        // 将图片转换为字节数据
        byte[] imgData = response.getBody();
        // 将字节数据转换为Base64字符串
        String base64Image = Base64.getEncoder().encodeToString(imgData);
        // 创建索引请求
        IndexRequest request = new IndexRequest("imgstore"); // 你的索引名
        request.id(System.currentTimeMillis()+""); // 文档ID
//        request.source("blob", base64Image, XContentType.JSON); // 图片字段名称和Base64字符串
        request.source("blob", base64Image);
//        request.source("name", System.currentTimeMillis()+"", XContentType.JSON);
        // 发送请求并获取响应
        IndexResponse response1 = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        // 输出结果
        System.out.println("Index response status: " + response1.getResult());
    }

    @PostMapping("/downFromEs")
    public void downFromEs(@RequestParam  String indexName,@RequestParam String id) throws Exception{
        // 创建请求
        GetRequest request = new GetRequest(indexName, id);
        // 客户端发送请求
        GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        System.out.println(response.getSourceAsString());
        JSONObject imgObject = JSON.parseObject(response.getSourceAsString());
        byte[] imageData = Base64.getDecoder().decode(imgObject.get("blob").toString());

        FileOutputStream fos = new FileOutputStream(id.substring(id.indexOf("_")+1)+".png");
        fos.write(imageData);
        fos.close();

    }

}
